package com.lovemanai.action;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements
	ServletResponseAware {
	
	/*
	 * 用户请求通过Struts2核心控制器转发到POJO，POJO中的属性封装页面提交过来的数据（属性必须提供getter，setter方法），POJO中
	 * 提供默认处理方法public String execute()用于处理用户请求
	 */
	
	private static final long serialVersionUID = 1L;
	
	
	private String username;
	private String password;
	private String tip;
	
	private HttpServletResponse response;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
	public String getTip() {
		return tip;
	}
	public void setTip(String tip) {
		this.tip = tip;
	}
	public String regist() {
		ActionContext atx = ActionContext.getContext();
		atx.getSession().put("username", getUsername());
		setTip("恭喜， " + getUsername() + " 已经成功注册");
		return SUCCESS;
	}
	
	//处理用户请求方法
	public String execute() {
		ActionContext atx = ActionContext.getContext();
		
		Integer counter = (Integer) atx.getApplication().get("counter");
		
		if(counter == null) {
			counter = 1;
		} else {
			counter = counter + 1;
		}
			
		atx.getApplication().put("counter", counter);//统计网站访问次数
		
		if(getUsername().equals("jerry") 
				&& getPassword().equals("666666")) {
			atx.getSession().put("username", getUsername());
			atx.put("tip", "您已经登录成功");//设置request范围内的属性
			Cookie cookie = new Cookie("username", getUsername());
			cookie.setMaxAge(10 * 60);
			response.addCookie(cookie);
			return SUCCESS;
		} else {
			atx.put("tip", "您还没有登录");
			return ERROR;
		}
		
	}
	
	@Override
	public void setServletResponse(HttpServletResponse response) {
		
		this.response = response;
	}

}
